//
//  ZGLRegisterController.m
//  ZeegingLottery
//
//  Created by 蒂埃里 on 2018/4/3.
//  Copyright © 2018年 蒂埃里. All rights reserved.
//

#import "ZGLRegisterController.h"
#import "ZGLRegisterView.h"

@interface ZGLRegisterController ()
{
    CGFloat offSet;
    CGFloat duration;
}

@property (strong, nonatomic)ZGLRegisterView *registerView;


@end

@implementation ZGLRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ViewBackgroundColor;
    self.title = @"注册";
    [self setLeftBackButtonWith:@"取消" Image:nil];
    [self.view addSubview:self.registerView];

    
    //即将显示的键盘
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
//    //即将推出的键盘
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


#pragma mark - notification meth

//
- (void)registerBtnAction:(UIButton *)sender
{
    DLog(@"注册");
    [self.view endEditing:YES];
    
    NSString *mobilePhone = self.registerView.accountTextField.text;
    NSString *VerificationCode = self.registerView.VerificationCodeTF.text;
    NSString *password = self.registerView.passwordTF.text;
    NSString *confirmPassword = self.registerView.confirmPasswordTF.text;
    BOOL isValidateMobile = [PublicMethod isValidateMobile:mobilePhone];
    
    if (mobilePhone.length <= 0 && !isValidateMobile) {
        
        DLog(@"请输入正确手机号");
        [EasyTextView showInfoText:@"请输入正确手机号"];
        
    }else if (VerificationCode.length != 6 ){
        
        DLog(@"请输入短信验证码");
        [EasyTextView showText:@"请获取短信验证码并输入"];
        
    }
    else if (password.length <= 0 && confirmPassword.length <= 0){
        
        [EasyTextView showText:@"请输入密码或确认密码"];
        
    }else if(![self.registerView.passwordTF.text isEqualToString:self.registerView.confirmPasswordTF.text]){
        
        [EasyTextView showInfoText:@"两次输入的密码不相同"];
        
    }else{
        
        [TalkingData trackEvent:ZGLRegistingBtnEventID];
        
        //密码做MD5
        NSString *Password = [PublicMethod MD5ForUpper32Bate:password];
        
        //发送注册请求
        [sZGLHTTPRequestManager registWithMobilePhone:mobilePhone Password:Password SmsVerifyCode:[VerificationCode intValue] RegisterChannel:2 Success:^(id responseData) {
            
            NSDictionary *successDict = responseData;
            NSString *code = successDict[@"code"];
            NSString *message = successDict[@"message"];
            if ([code integerValue] == 1) {
                
                //注册成功埋点
                [TalkingData onRegister:mobilePhone type:TDAccountTypeRegistered name:nil];
                
                DLog(@"注册成功");
                [EasyTextView showSuccessText:@"注册成功" config:^EasyTextConfig *{
                    
                    EasyTextConfig *config = [EasyTextConfig shared];
                    config.shadowColor = [UIColor redColor];
                    config.bgColor = [UIColor lightGrayColor];
                    
                    return config;
                }];
                

                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    
                    NSString *deviceName = [PublicMethod currentDeviceName];
                    NSString *deviceModel = [PublicMethod currentDeviceModel];
                    [sZGLHTTPRequestManager loginWithMobilPhone:mobilePhone Password:Password LoginType:@"password_login" DeviceName:deviceName DeviceModel:deviceModel Success:^(id responseData){
                        
                        DLog(@"登录成功");
                        NSString *code = responseData[@"code"];
                        
                        //登录成功埋点
                        [TalkingData onLogin:mobilePhone type:TDAccountTypeRegistered name:nil];
                        
                        if ([code integerValue] == 1) {
                            
                            NSDictionary *data = responseData[@"data"];
                            ZGLUserInfoModel *model = [ZGLUserInfoModel mj_objectWithKeyValues:data];
                            [sZGLUserInfoModel setLoginSuccessedWithUserInfo:model];
                        }
                        
                    } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
                        
                        DLog(@"登录失败");
                        
                    }];
                    
                });
                
                
                //注册成功返回主界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
                
                
                
            }else if ([code integerValue] == 0 && [message isEqualToString:@"该手机号已经存在"]) {
                DLog(@"注册失败,该手机号已经存在");
                [EasyAlertView alertViewWithPart:^EasyAlertPart *{
                    
                    return [EasyAlertPart shared].setTitle(@"注册失败").setSubtitle(@"该手机号已经存在,请返回登录").setAlertType(AlertViewTypeSystemAlert);
                    
                } config:^EasyAlertConfig *{
                    
                    UIColor *tintC = [UIColor groupTableViewBackgroundColor];
                    return [EasyAlertConfig shared].settwoItemHorizontal(YES).setAnimationType(AlertAnimationTypeFade).setTintColor(tintC).setBgViewEvent(NO).setSubtitleTextAligment(NSTextAlignmentLeft).setEffectType(AlertBgEffectTypeAlphaCover);
                    
                } buttonArray:^NSArray<NSString *> *{
                    
                    return @[@"确定"];
                    
                } callback:^(EasyAlertView *showview, long index) {
                    
                    [self goBack];
                }];
                
            }else if ([code integerValue] == 0 && [message isEqualToString:@"短信验证码错误"]){
                
                [EasyTextView showInfoText:@"短信验证码错误"];
                
            }else{
                
                DLog(@"注册失败，请重试");
                [EasyTextView showErrorText:@"注册失败，请重试" config:^EasyTextConfig *{
                    
                    EasyTextConfig *config = [EasyTextConfig shared];
                    config.shadowColor = [UIColor redColor];
                    config.bgColor = [UIColor lightGrayColor];
                    
                    return config;
                }];
                
            }
            
            

        } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
            DLog(@"注册失败");
            
            [EasyTextView showErrorText:@"注册失败" config:^EasyTextConfig *{
                
                EasyTextConfig *config = [EasyTextConfig shared];
                config.shadowColor = [UIColor redColor];
                config.bgColor = [UIColor lightGrayColor];
                
                return config;
            }];
        }];
    }
}

//
- (void)getVerificationCode:(UIButton *)sender
{
    DLog(@"获取验证码");
    BOOL isValidateMobile = false;
    NSString *mobilePhone = self.registerView.accountTextField.text;
    if (mobilePhone.length <= 0) {
        DLog(@"请输入手机号");
        [EasyTextView showText:@"请输入手机号"];
        
    }else{
        
        [TalkingData trackEvent:ZGLRegistingBtnEventID label:sender.titleLabel.text];
        
        isValidateMobile = [PublicMethod isValidateMobile:mobilePhone];
        if (isValidateMobile) {
            
            
            //发送请求
            [sZGLHTTPRequestManager getVerificationCodeWithPhoneNum:mobilePhone Success:^{
                
                [EasyTextView showSuccessText:@"短信以发送，请查收"];
                [sender startCountdownTime:countDownTime withCountDownBlock:nil];//倒计时
                
                
            } Fail:^(ZGLRespondStatusCode bef_status, NSString *bef_message, NSError *error) {
                
                [EasyTextView showErrorText:@"短信发送失败，请检查网络"];
                
            }];
            
        }else{
            DLog(@"请输入正确的手机号");
            [EasyTextView showInfoText:@"请输入正确的手机号"];
            
        }
    }
}

//取消
- (void)goBack
{
    [TalkingData trackEvent:ZGLRegistingBtnEventID label:@"cancel"];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - getter

- (ZGLRegisterView *)registerView
{
    if (!_registerView) {
        _registerView = [[ZGLRegisterView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
        [_registerView.registeButton addTarget:self action:@selector(registerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [_registerView.getVerificationCodeBtn addTarget:self action:@selector(getVerificationCode:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _registerView;
}


- (void)dealloc {
    DLog(@"%s",__func__);
    
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
